import { extendApi } from '@inbiz/utils';
export default extendApi((_events: any, { dataList: option, $dataList, props, state }) => {
  return {
    loadData: (list: any) => {
      $dataList(list);
    },
    getData: () => {
      return option;
    },
    getText: () => {
      if (Array.isArray(state.value)) {
        return option
          ?.filter((item: any) => state.value.includes(item.value))
          .map((item: any) => item.label ?? item.text);
      } else {
        const data = option?.find((item: any) => item.value === state.value);
        return data?.label ?? data?.text;
      }
    },
    getSaveData: () => {
      let propsValue = props.value;
      if (props.storageConfig && props.childModelConfig) {
        let dataList: any[] = [];
        if (typeof propsValue == 'string' && propsValue !== '') {
          propsValue = propsValue.split(',');
          propsValue = propsValue.map((item: string) => item.trim());
        }
        if (Array.isArray(propsValue)) {
          dataList = propsValue.map((item: string) => {
            let fil = option.filter((val: { value: string }) => val.value === item);
            return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
              pre[next.modelAttr] = fil[0][next.componentAttr];
              if (next.componentAttr == 'text' && pre[next.modelAttr] === undefined) {
                pre[next.modelAttr] = fil[0]['label'];
              }
              pre['_opt'] = 'add';
              return pre;
            }, {});
          });
        }
        const data = {
          value: Array.isArray(propsValue) ? propsValue.join(',') : propsValue,
          childData: props.storageConfig
            ? {
                controlId: props.controlId,
                modelKey: props.storageConfig?.business,
                datas: [
                  ...dataList,
                  {
                    _opt: 'del',
                  },
                ],
              }
            : undefined,
        };
        return data;
      }
      return {
        value: Array.isArray(propsValue) ? propsValue.join(',') : propsValue,
      };
    },
  };
});
